package org.rain.core.querygen.support;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.rain.common.util.Strs;
import org.rain.core.querygen.AbsQueryCondition;
import org.rain.core.querygen.token.Token;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * created by yangtong on 2025/4/6 下午10:36
 * <p>
 * 模糊查询，支持全模糊，左模糊，右模糊，name=*张三*
 * <p>
 * 优先级仅次于等值查询
 */
@Component
public class LikeQueryCondition extends AbsQueryCondition implements Ordered {
    @Override
    public Boolean isMatch(Token token) {
        return Strs.isNotEmpty(token.getValue()) && token.getValue().startsWith("*") && token.getValue().endsWith("*");
    }

    @Override
    public <T> QueryWrapper<T> genQueryWrapper(QueryWrapper<T> queryWrapper, Token token) {
        //移除value前后的*号
        token.setValue(token.getValue().substring(1, token.getValue().length() - 1));
        return positiveOrNegate(queryWrapper, token);

    }

    @Override
    protected <T> QueryWrapper<T> positive(QueryWrapper<T> queryWrapper, Token token) {
        return queryWrapper.like(Strs.toUnderline(token.getKey()), token.getValue());
    }

    @Override
    protected <T> QueryWrapper<T> negate(QueryWrapper<T> queryWrapper, Token token) {
        return queryWrapper.not(w -> w.like(Strs.toUnderline(token.getKey()), token.getValue()));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
